<template>
  <div>
    <BasicModal v-bind="$attrs" v-model:visible="showContract" :title="getTitle()" @ok="onSubmit">
      <Form
        class="form_box"
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 14 }"
      >
        <FormItem label="验收类型" name="types">
          <CheckboxGroup
            :options="typesPptions"
            v-model:value="formState.types"
            placeholder="请选择验收类型"
          >
            <!-- <Checkbox value="10">基槽验收</Checkbox>
            <Checkbox value="11">基础验收</Checkbox>
            <Checkbox value="12">主体验收</Checkbox>
            <Checkbox value="13">竣工验收</Checkbox> -->
          </CheckboxGroup>
        </FormItem>
        <FormItem label="盖章类型" name="seals">
          <CheckboxGroup v-model:value="formState.seals" placeholder="请选择盖章类型">
            <Checkbox value="10">公章</Checkbox>
            <Checkbox value="11">技术章</Checkbox>
          </CheckboxGroup>
        </FormItem>
        <FormItem label="资质公司编号" name="licenseCompanyId">
          <Select
            allowClear
            v-model:value="formState.licenseCompanyId"
            placeholder="请选择资质公司编号"
          >
            <SelectOption v-for="(item, index) in allLicense" :value="item.id" :key="index">{{
              item.name
            }}</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="盖章时间" name="signDate">
          <DatePicker
            :format="'YYYY-MM-DD'"
            valueFormat="YYYY-MM-DD"
            v-model:value="formState.signDate"
          />
        </FormItem>
        <FormItem label="验收数量" name="number">
          <Input v-model:value="formState.number" placeholder="请输入验收数量" types="number" />
        </FormItem>
        <FormItem label="附件" name="urlFile">
          <Upload
            :multiple="true"
            :before-upload="beforeUpload"
            :file-list="formState.urlFile"
            @change="handleChange"
          >
            <a-button>
              <upload-outlined></upload-outlined>
              上传附件
            </a-button>
          </Upload>
        </FormItem>
      </Form>
    </BasicModal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
  import {
    Form,
    Input,
    FormItem,
    DatePicker,
    Upload,
    Select,
    SelectOption,
    Checkbox,
    CheckboxGroup,
  } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicModal } from '/@/components/Modal';
  import { fileUploadApi, fileViewApi } from '/@/api/projectManagement';
  import { useRoute } from 'vue-router';
  import {
    addcheckRecord,
    editcheckRecord,
    addApplycheckRecord,
    editApplycheckRecord,
  } from '/@/api/api';

  const typesPptions = [
    { label: '基槽验收', value: '10' },
    { label: '基础验收', value: '11' },
    { label: '主体验收', value: '12' },
    { label: '竣工验收', value: '13' },
  ];
  const instance = getCurrentInstance();
  let route = useRoute();

  const { createMessage } = useMessage();

  const formRef = ref();
  const formState = reactive({
    projectId: '',
    types: [],
    seals: [],
    signDate: '',
    number: '',
    url: '',
    urlFile: [],
    licenseCompanyId: '',
  });
  onMounted(() => {
    console.log(route.query, 'query');
  });
  let validatePass2 = () => {
    if (formState.urlFile.length <= 0) {
      return Promise.reject('请上传验收附件');
    } else {
      return Promise.resolve();
    }
  };
  const getTitle = () => {
    const baseText = isEdit.value ? '编辑' : '添加';
    const recordType = projectKind.value === 'partner' ? '申请验收记录' : '验收记录';
    return `${baseText}${recordType}`;
  };
  const rules = {
    types: [{ required: true, message: '请选择验收类型' }],
    seals: [{ required: true, message: '请选择盖章类型' }],
    signDate: [{ required: true, message: '请选择验收盖章时间' }],
    licenseCompanyId: [{ required: true, message: '请选择资质公司编号' }],
    number: [{ required: true, message: '请输入验收数量' }],
    urlFile: [{ required: true, validator: validatePass2, trigger: 'change' }],
  };

  const beforeUpload = (file) => {
    let formData = new FormData();
    formData.append('file', file);
    fileUploadApi(formData).then((res) => {
      formState.urlFile = [file];
      formState.url = res;
      formRef.value.clearValidate('urlFile');
    });

    return false;
  };
  const handleChange = (info) => {
    if (info.file.status == 'removed') {
      formState.urlFile = [];
    }
  };

  const showContract = ref(false);
  const allLicense = ref([]);

  const projectKind = ref();
  const kindName = ref();
  const init = (data) => {
    console.log(data);
    allLicense.value = data.allLicense;
    showContract.value = true;
    formState.projectId = data.projectId;
    // partner 为合伙人，公司项目不传
    projectKind.value = data.projectKind;
    if (data.isEdit == true) {
      isEdit.value = true;
      editData.value = data.editData;
      kindName.value = projectKind.value == 'partner' ? 'checkApplyResponse' : 'checkResponse';
      formState.number = editData.value[kindName.value].number;
      formState.signDate = editData.value[kindName.value].signDate;
      formState.types = editData.value[kindName.value].types;
      formState.seals = editData.value[kindName.value].seals;
      formState.url = editData.value[kindName.value].url;
      formState.licenseCompanyId = editData.value[kindName.value].licenseCompanyId;
      fileViewApi(formState.url).then((res) => {
        let nameExtension = formState.url.split('.')[1];
        let file = new File([res], `验收附件.${nameExtension}`, { types: nameExtension }); // 创建一个File对象
        file.uid = 'v-' + Date.now();
        formState.urlFile = [file];
        console.log(file, '图片');
      });
    } else {
      isEdit.value = false;
      editData.value = {};
      resetForm();
    }
  };
  const isEdit = ref(false);
  const editData = ref({});

  const onSubmit = () => {
    formRef.value
      .validate()
      .then(() => {
        // editcheckRecord
        if (isEdit.value == true) {
          const { urlFile, ...restFormState } = formState;
          if (projectKind.value == 'partner') {
            editApplycheckRecord({
              ...restFormState,
              id: editData.value[kindName.value].id,
            }).then((res) => {
              if (res != false) {
                createMessage.success('编辑成功');
                if (instance) {
                  instance.proxy?.$emit('tableNeedUpdate');
                }
                resetForm();
                showContract.value = false;
              }
            });
          } else {
            editcheckRecord({
              ...restFormState,
              id: editData.value[kindName.value].id,
            }).then((res) => {
              if (res != false) {
                createMessage.success('编辑成功');
                if (instance) {
                  instance.proxy?.$emit('tableNeedUpdate');
                }
                resetForm();
                showContract.value = false;
              }
            });
          }
          editcheckRecord({
            ...restFormState,
            id: editData.value[kindName.value].id,
          }).then((res) => {
            if (res != false) {
              createMessage.success('编辑成功');
              if (instance) {
                instance.proxy?.$emit('tableNeedUpdate');
              }
              resetForm();
              showContract.value = false;
            }
          });
        } else {
          const { urlFile, ...restFormState } = formState;
          // if (projectKind.value == 'partner') {

          // } else {

          // }
          if (projectKind.value == 'partner') {
            addApplycheckRecord({
              ...restFormState,
            }).then((res) => {
              if (res != false) {
                createMessage.success('添加成功');
                resetForm();
                showContract.value = false;
                if (instance) {
                  instance.proxy?.$emit('tableNeedUpdate');
                }
              }
            });
          } else {
            addcheckRecord({
              ...restFormState,
            }).then((res) => {
              if (res != false) {
                createMessage.success('添加成功');
                resetForm();
                showContract.value = false;
                if (instance) {
                  instance.proxy?.$emit('tableNeedUpdate');
                }
              }
            });
          }
        }
      })
      .catch((error: any) => {
        console.log('error', error);
      });
  };
  const resetForm = () => {
    formState.number = '';
    formState.signDate = '';
    formState.types = [];
    formState.seals = [];
    formState.url = '';
    formState.urlFile = [];
    formState.licenseCompanyId = '';
  };

  defineExpose({
    init,
  });
</script>
